﻿using System;
using System.Threading;

using Sunyi.Project.WebPoint.BusinessLogic;
using Sunyi.Project.WebPoint.Common;
using Sunyi.Project.WebPoint.Configuration;
using Sunyi.Project.WebPoint.DataContract;
using Sunyi.Project.WebPoint.Resource;
using Sunyi.Project.WebPoint.WebControl;

namespace ActivitySystem.Web.Account
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.Page.Form.DefaultFocus = tbxUserName.ClientID;
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string userName = tbxUserName.Text;
            string password = tbxPassword.Text;

            try
            {
                var authenticationManager = new AuthenticationManager();
                bool flag = authenticationManager.ValidateUser(userName, password);

                if (flag)
                {
                    UserManager userManager = new UserManager();
                    userManager.Login(userName);

                    Session[WebPointGlobalConstant.Session_CurrentUser] = userManager.SelectByName(userName);

                    if (!string.IsNullOrEmpty(Request.Params[WebPointGlobalConstant.ReturnUrl]))
                    {
                        Response.Redirect(Request.Params[WebPointGlobalConstant.ReturnUrl], false);
                    }
                    else
                    {
                        Response.Redirect(SystemConfiguration.WebSite[WebPointGlobalConstant.HomePage], false);
                    }
                }
                else
                {
                    WebControlCommon.ShowClientMessage(this, WebResource.LoginFailed);
                }

                WriteLoginAuditLog(userName, flag);
            }
            catch (Exception ex)
            {
                ExceptionHandler.Handle(this, ex);
            }
        }

        private void WriteLoginAuditLog(string userName, bool result)
        {
            AuditLog auditLog = new AuditLog();
            auditLog.OperationCode = AuditLogOperationCode.Login.ToString();
            auditLog.Source = this.GetType().Name;
            auditLog.Category = string.Empty;
            auditLog.Data = result.ToString() + WebPointGlobalConstant.Enter + Request.UserHostAddress;
            auditLog.Category = result.ToString();
            auditLog.UserName = userName;

            AuditLogger.Write(auditLog);
        }
    }
}
